package com.framework.spring.mybatis.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MysqlSession {

	public static <T> T getMapper(Class<T> clazz) {
		ClassLoader classLoader = MysqlSession.class.getClassLoader();
		Class[] classes = new Class[]{clazz};
		T o = (T) Proxy.newProxyInstance(classLoader, classes, new MyInvocationHandler());
		return o;
	}

	@Slf4j(topic = "e")
	static class MyInvocationHandler implements InvocationHandler {
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			if (method.getDeclaringClass().equals(Object.class)) {
				method.invoke(this, args);
			}

			Select select = method.getAnnotation(Select.class);
			String sql = select.value()[0];
			log.info("需要查询的sql:{}", sql);
			List<Map<String, Object>> list = new ArrayList<>();
			Map<String, Object> map1 = new HashMap<>();
			map1.put("id", 1);
			map1.put("name", "1");
			map1.put("age", 1);
			Map<String, Object> map2 = new HashMap<>();
			map2.put("id", 2);
			map2.put("name", "2");
			map2.put("age", 2);
			list.add(map1);
			list.add(map2);
			return list;
		}
	}
}
